package net.tv90.appserveradmin.controller.common;

import cn.dev33.satoken.annotation.SaCheckLogin;
import net.tv90.appserveradmin.exception.ServerException;
import net.tv90.appserveradmin.model.Users;
import net.tv90.appserveradmin.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Validated
@Controller
public class LoginController {

    @Autowired
    UserService userService;

    @GetMapping("/index/login")
    public String login() {
        return "common/login";
    }

    @PostMapping("/login")
    public String loginUser(String userId, String password, Model model) {
        try {
            System.out.println(userId + " " + password);
            userService.login(userId, password);
        } catch (ServerException e) {
            model.addAttribute("errMsg", e.getMessage());
            return "common/login";
        }
        model.addAttribute("userId", userId);
        return "redirect:/";
    }

    @GetMapping("/logout")
    @SaCheckLogin
    public String logoutUser() {
        try {
            userService.logout();
        } catch (ServerException e) {
            return "redirect:/";
        }
        return "redirect:/";
    }

    @GetMapping("/currentUser")
    @ResponseBody
    public String getCurrentUser() {
        Users user = userService.getCurrentUser();
        return (user == null) ? "未登录" : user.getUserId();
    }

}
